<template>
  <div class="mental-health-container">
    <a-card title="心理健康测评" :bordered="false">
      <div class="input-section">
        <a-textarea
          v-model:value="userDescription"
          placeholder="请输入您当前的心情描述（例如：开心、焦虑、压力大等）"
          :rows="4"
          allow-clear
        />
        <a-button
          type="primary"
          @click="generateQuestions"
          :loading="generating"
          style="margin-top: 16px"
        >
          生成测试题
        </a-button>
      </div>

    

      <!-- 测试题弹窗 -->
      <a-modal
        v-model:visible="questionModalVisible"
        title="心理健康测评"
        width="800px"
        :footer="null"
        :maskClosable="false"
      >
        <div v-if="questions.length > 0">
          <div v-for="(question, index) in questions" :key="question.id" class="question-item">
            <h3>{{ index + 1 }}. {{ question.question }}</h3>
            <a-radio-group
              v-model:value="question.selectedOption"
              @change="(e) => handleAnswerChange(question.id, e.target.value)"
            >
              <a-space direction="vertical">
                <a-radio
                  v-for="option in question.options"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-radio>
              </a-space>
            </a-radio-group>
          </div>

          <div class="action-buttons">
            <a-button type="primary" @click="submitAnswers" :disabled="!allAnswered">
              提交测评
            </a-button>
            <a-button style="margin-left: 16px" @click="questionModalVisible = false">
              取消
            </a-button>
          </div>
        </div>
        <a-skeleton v-else active :paragraph="{ rows: 10 }" />
      </a-modal>

      <!-- 结果展示弹窗 -->
      <a-modal
        v-model:visible="resultModalVisible"
        title="测评结果"
        width="1500px"
        :footer="null"
      >
        <div v-if="analysisResult">
          <a-alert
            :message="`风险等级: ${analysisResult.riskLevel}`"
            :type="getRiskLevelType(analysisResult.riskLevel)"
            show-icon
            style="margin-bottom: 16px"
          />
          <a-card title="分析结果" style="margin-bottom: 16px">
            <div v-html="analysisHtml" />
          </a-card>
          <a-card title="建议">
            <div v-html="suggestionHtml" />
          </a-card>
        </div>
        <a-skeleton v-else active :paragraph="{ rows: 4 }" />
      </a-modal>
    </a-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import { useMarkdownRender } from './useMarkdownRender'

const userDescription = ref('')
const generating = ref(false)
const questionModalVisible = ref(false)
const resultModalVisible = ref(false)
const questions = ref([])
const mentalHealthSelfAssessmentId = ref(null)
const analysisResult = ref(null)
const { html: analysisHtml, renderMarkdown: renderAnalysis } = useMarkdownRender()
const { html: suggestionHtml, renderMarkdown: renderSuggestion } = useMarkdownRender()

// 检查是否所有问题都已回答
const allAnswered = computed(() => {
  return questions.value.length > 0 && questions.value.every(q => q.selectedOption !== undefined)
})

// 生成测试题
const generateQuestions = async () => {
    console.log('Generating questions with description:', userDescription.value)
  if (!userDescription.value.trim()) {
    message.warning('请输入您的心情描述')
    return
  }
  generating.value = true
  try {
    const response = await axios.post('http://192.168.0.22:7044/api/module/AIMentalHealth', {
      userDescription: userDescription.value
    })
    if (response.data.success) {
      questions.value = response.data.data.psychologicalQuestion.map(q => ({
        ...q,
        selectedOption: undefined
      }))
      mentalHealthSelfAssessmentId.value = response.data.data.mentalHealthSelfAssessmentId
      questionModalVisible.value = true
    } else {
      message.error(response.data.message || '生成测试题失败')
    }
  } catch (error) {
    console.error('生成测试题出错:', error)
    message.error('生成测试题出错，请稍后重试')
  } finally {
    generating.value = false
  }
}

// 记录用户选择的答案
const handleAnswerChange = (questionId, optionValue) => {
  const question = questions.value.find(q => q.id === questionId)
  if (question) {
    question.selectedOption = optionValue
  }
}

// 提交答案
const submitAnswers = async () => {
  if (!allAnswered.value) {
    message.warning('请回答所有问题后再提交')
    return
  }
  try {
    const response = await axios.post('http://192.168.0.22:7044/api/module/AIMentalHealth/Analyze', {
      mentalHealthSelfAssessmentId: mentalHealthSelfAssessmentId.value,
      answers: questions.value.map(q => ({
        questionId: q.id,
        selectedOption: q.selectedOption
      })),
      userDescription: userDescription.value,
    })
    if (response.data.success) {
      analysisResult.value = response.data.data
      renderAnalysis(response.data.data.analysis)
      renderSuggestion(response.data.data.suggestion)
      userDescription.value = '' // 清空输入框
      resultModalVisible.value = true
      questionModalVisible.value = false
    } else {
      message.error(response.data.message || '提交失败')
    }
  } catch (error) {
    console.error('提交答案出错:', error)
    message.error('提交答案出错，请稍后重试')
  }
}

const getRiskLevelType = (type) => {
  switch (type) {
    case 1:
      return '低风险'
    case 2:
      return '中风险'
    case 3:
      return '高风险'
    default:
      return '未知'
  }
}
</script>

<style scoped>
.mental-health-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
}

.input-section {
  margin-bottom: 24px;
}

.question-item {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.question-item h3 {
  margin-bottom: 12px;
}

.action-buttons {
  margin-top: 24px;
  text-align: center;
}
</style>